package com.cy.aircompressor.main.ui.lifecycle.fragment.dialog;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;

import com.cy.aircompressor.config.AirConfig;
import com.cy.aircompressor.databinding.DialogNewMaintenanceFragmentBinding;
import com.cy.aircompressor.databinding.MaintenanceStepFourViewBinding;
import com.cy.aircompressor.databinding.MaintenanceStepOneViewBinding;
import com.cy.aircompressor.databinding.MaintenanceStepThreeViewBinding;
import com.cy.aircompressor.databinding.MaintenanceStepTwoViewBinding;
import com.cy.aircompressor.entity.component.Component;
import com.cy.aircompressor.entity.select.SelectDict;
import com.cy.aircompressor.entity.sensor.Sensor;
import com.cy.aircompressor.main.ui.lifecycle.fragment.provider.ComponentProvider;
import com.cy.aircompressor.main.ui.lifecycle.fragment.provider.SensorProvider;
import com.cy.aircompressor.main.ui.lifecycle.viewmodel.LifeCycleViewModel;
import com.cy.aircompressor.main.view.pop.AirDropdownPopupWindow;
import com.drug.lib.util.ToastUtil;
import com.drug.lib.view.recycptr.DynamicAdpTypePool;
import com.drug.lib.view.recycptr.DynamicRecyclerAdapter;
import com.drug.lib.view.recycptr.bean.RowEntity;
import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.net.model.base.Resource;
import com.net.model.base.fragment.BaseVMDialogFragment;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function5;

public class NewMaintenanceFragment extends BaseVMDialogFragment<DialogNewMaintenanceFragmentBinding, LifeCycleViewModel> {
    SelectDict compressor;
    MaintenanceStepFourViewBinding fourViewBinding;
    MaintenanceStepThreeViewBinding threeViewBinding;
    MaintenanceStepTwoViewBinding twoViewBinding;
    MaintenanceStepOneViewBinding oneViewBinding;


    public static void showDialogFragment(FragmentManager fragmentManager, String tag) {
        Bundle args = new Bundle();
        NewMaintenanceFragment fragment = new NewMaintenanceFragment();
        fragment.setArguments(args);
        fragment.show(fragmentManager, tag);
    }

    @Override
    protected void dataChange() {
        mViewModel.getQueryComponentByPageObservable().observe(this, new Observer<Resource<RowEntity<Component>>>() {
            @Override
            public void onChanged(Resource<RowEntity<Component>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<RowEntity<Component>>() {
                    @Override
                    public void onSuccess(RowEntity<Component> data) {
                        componentRecyclerAdapter.setItems(data.getList());
                        componentRecyclerAdapter.notifyDataSetChanged();
                    }
                });
            }
        });
        mViewModel.getQuerySensorByPageObservable().observe(this, new Observer<Resource<RowEntity<Sensor>>>() {
            @Override
            public void onChanged(Resource<RowEntity<Sensor>> rowEntityResource) {
                rowEntityResource.handler(new OnCallback<RowEntity<Sensor>>() {
                    @Override
                    public void onSuccess(RowEntity<Sensor> data) {
                        sensorRecyclerAdapter.setItems(data.getList());
                        sensorRecyclerAdapter.notifyDataSetChanged();
                    }
                });
            }
        });
    }

    @Override
    protected DialogNewMaintenanceFragmentBinding getViewBinding() {
        return DialogNewMaintenanceFragmentBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        initView();

    }

    @Override
    protected void requestNetwork() {

    }

    @Override
    protected int getWindowHeight() {
        return getScreenHeight() - 50;
    }

    private void initView() {
        initFirstStep();
        initSecondStep();
        initThirdStep();
        initFourStep();
        initStep();
        RxView.clicks(mBinding.nextStep)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    nextStep();
                });
        RxView.clicks(mBinding.returnStep)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    returnStep();
                });
        RxView.clicks(mBinding.closeBtn)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    dismiss();
                });
    }

    private Map<Integer, View> stepMap = new HashMap<>();
    private Map<Integer, ViewBinding> contentMap = new HashMap<>();
    private int step = 0;

    private void initStep() {
        stepMap.put(0, mBinding.step1View);
        stepMap.put(1, mBinding.step2View);
        stepMap.put(2, mBinding.step3View);
        stepMap.put(3, mBinding.step4View);

        contentMap.put(0, oneViewBinding);
        contentMap.put(1, twoViewBinding);
        contentMap.put(2, threeViewBinding);
        contentMap.put(3, fourViewBinding);

        stepMap.forEach(new BiConsumer<Integer, View>() {
            @Override
            public void accept(Integer integer, View view) {
                view.setSelected(integer == step ? true : false);
            }
        });
        showStepContent();
        mBinding.returnStep.setVisibility(View.GONE);
    }

    /**
     * 点击下一步
     */
    private void nextStep() {
        if (step >= stepMap.size() - 1) return;
        switch (step) {
            case 0:
                if (!mBinding.nextStep.isEnabled()) {
                    ToastUtil.show("请按照要求填写完整！");
                    return;
                }
                stepMap.get(++step).setSelected(true);
                showStepContent();
                mBinding.returnStep.setVisibility(View.VISIBLE);
                mViewModel.queryComponentByPage(1, 100, compressor.getValue(), AirConfig.get().userInfo.getPowerStationId(), null, null);
                break;
            case 1:
                stepMap.get(++step).setSelected(true);
                showStepContent();
                mViewModel.querySensorByPage(1, 100, compressor.getValue(), AirConfig.get().userInfo.getPowerStationId(), null, null);
                break;
            case 2:
                stepMap.get(++step).setSelected(true);
                showStepContent();
                mBinding.nextStep.setText("确认");
                break;
            case 3:
                dismiss();
                break;

        }
    }

    /**
     * 返回上一步
     */
    private void returnStep() {
        if (step > 0) {
            stepMap.get(step).setSelected(false);
            step--;
            showStepContent();
            mBinding.returnStep.setVisibility(step == 0 ? View.GONE : View.VISIBLE);
            mBinding.nextStep.setText(step == 3 ? "确认完成" : "确认完成，下一步");
        }
    }

    /**
     * 显示step对应的内容区视图
     */
    private void showStepContent() {
        addContainerView(contentMap.get(step).getRoot());
    }


    private void initFirstStep() {
        oneViewBinding = MaintenanceStepOneViewBinding.inflate(getLayoutInflater());

        RxView.clicks(oneViewBinding.selectedAir)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    AirDropdownPopupWindow mPopupWindow = new AirDropdownPopupWindow(mContext, oneViewBinding.selectedAir, oneViewBinding.selectedAir, AirConfig.get().compressors);
                    mPopupWindow.setDropdownCallBack(new AirDropdownPopupWindow.DropdownCallBack() {
                        @Override
                        public void select(SelectDict selectDict) {
                            compressor = selectDict;
                        }
                    });
                    mPopupWindow.showAsDropDown(oneViewBinding.selectedAir);//显示PopupWindow小弹窗
                });
        RxView.clicks(oneViewBinding.startTime)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    showDatePicker(oneViewBinding.startTime);
                });
        RxView.clicks(oneViewBinding.endTime)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    showDatePicker(oneViewBinding.endTime);
                });
        RxView.clicks(oneViewBinding.nextMaintenance)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    showDatePicker(oneViewBinding.nextMaintenance);
                });

        Observable<CharSequence> selectedAir = RxTextView.textChanges(oneViewBinding.selectedAir);
        Observable<CharSequence> startTime = RxTextView.textChanges(oneViewBinding.startTime);
        Observable<CharSequence> endTime = RxTextView.textChanges(oneViewBinding.endTime);
        Observable<CharSequence> operator = RxTextView.textChanges(oneViewBinding.operator);
        Observable<CharSequence> nextMaintenance = RxTextView.textChanges(oneViewBinding.nextMaintenance);
        Observable.combineLatest(selectedAir, startTime, endTime, operator, nextMaintenance, new Function5<CharSequence, CharSequence, CharSequence, CharSequence, CharSequence, Boolean>() {
            @NonNull
            @Override
            public Boolean apply(@NonNull CharSequence charSequence, @NonNull CharSequence charSequence2, @NonNull CharSequence charSequence3, @NonNull CharSequence charSequence4, @NonNull CharSequence charSequence5) throws Exception {

                return !TextUtils.isEmpty(charSequence) && !TextUtils.isEmpty(charSequence2) &&
                        !TextUtils.isEmpty(charSequence3) && !TextUtils.isEmpty(charSequence4) &&
                        !TextUtils.isEmpty(charSequence5);
            }
        }).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                mBinding.nextStep.setEnabled(aBoolean);
            }
        });
    }

    private void initSecondStep() {
        twoViewBinding = MaintenanceStepTwoViewBinding.inflate(getLayoutInflater());
        initComponentRecyclerAdapter(twoViewBinding.componentList);
    }

    private void initThirdStep() {
        threeViewBinding = MaintenanceStepThreeViewBinding.inflate(getLayoutInflater());
        initSensorRecyclerAdapter(threeViewBinding.sensorList);
    }

    private void initFourStep() {
        fourViewBinding = MaintenanceStepFourViewBinding.inflate(getLayoutInflater());
    }

    protected void addContainerView(View view) {
        mBinding.containerLl.removeAllViews();
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        mBinding.containerLl.addView(view, layoutParams);
    }

    private void showDatePicker(TextView textView) {
        Calendar calendar = Calendar.getInstance();
        // 弹出对话框
        DatePickerDialog datePickerDialog = new DatePickerDialog(mContext,DatePickerDialog.THEME_DEVICE_DEFAULT_LIGHT,
                null,
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
//        datePickerDialog.getDatePicker().setCalendarViewShown(true);
//        datePickerDialog.getDatePicker().setSpinnersShown(false);
        datePickerDialog.show();

        // 确认按钮
        datePickerDialog.getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
            @Override
            public void onClick(View v) {
                // 确认年月日
                int year = datePickerDialog.getDatePicker().getYear();
                int monthOfYear = datePickerDialog.getDatePicker().getMonth() + 1;
                int dayOfMonth = datePickerDialog.getDatePicker().getDayOfMonth();
                String date = formatDate(year, monthOfYear, dayOfMonth);
                textView.setText(date);
                // 关闭dialog
                datePickerDialog.dismiss();
            }
        });
    }

    private String formatDate(int year, int monthOfYear, int dayOfMonth) {
        return year + "-" + String.format(Locale.getDefault(), "%02d-%02d", monthOfYear, dayOfMonth);
    }


    DynamicRecyclerAdapter componentRecyclerAdapter;

    private void initComponentRecyclerAdapter(RecyclerView recyclerView) {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(mLayoutManager);
        componentRecyclerAdapter = new DynamicRecyclerAdapter();
        DynamicAdpTypePool pool = new DynamicAdpTypePool();
        ComponentProvider componentProvider = new ComponentProvider(mContext);
        pool.register(Component.class, componentProvider);
        componentRecyclerAdapter.registerAll(pool);
        recyclerView.setAdapter(componentRecyclerAdapter);
    }

    DynamicRecyclerAdapter sensorRecyclerAdapter;

    private void initSensorRecyclerAdapter(RecyclerView recyclerView) {
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(mLayoutManager);
        sensorRecyclerAdapter = new DynamicRecyclerAdapter();
        DynamicAdpTypePool pool = new DynamicAdpTypePool();
        SensorProvider sensorProvider = new SensorProvider(mContext);
        pool.register(Sensor.class, sensorProvider);
        sensorRecyclerAdapter.registerAll(pool);
        recyclerView.setAdapter(sensorRecyclerAdapter);
    }
}
